import { createRouter, createWebHistory } from "vue-router";

import LoginPage from "@/pages/login.vue";
import HomePage from "@/pages/home.vue";

const routes = [
  {
    path: "/",
    component: HomePage,
    meta: { requiresAuth: true }, // 添加一个 meta 字段来标识需要认证的路由
  },
  {
    path: "/login",
    component: LoginPage,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    const token = localStorage.getItem("token")

    if (!token) {
      next({
        path: "/login",
        query: { redirect: to.fullPath }, // 将目标页面路由传递给登录页面，登录成功后再重定向回来
      });
    } else {
      // 验证 token（这里只是示例，通常你需要在服务器端验证 token）
      // 如果 token 有效，则继续路由
      next();
    }
  } else {
    // 不需要认证页面
    next();
  }
});

export default router;
